package zz.demo.springCloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import zz.demo.springCloud.dao.UserDao;
import zz.demo.springCloud.entity.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by zhangzheng on 2017-5-27.
 */
@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    @HystrixCommand
    @GetMapping(value = "/user/{id}")
    public User getUser(@PathVariable("id")Long id){
        return userDao.findById(id);
    }

    @GetMapping(value = "/addUser")
    public User addUser(User user){
        return user;
    }

    @GetMapping(value = "/add/{a}/{b}")
    public Integer add(@PathVariable("a")Integer a,@PathVariable("b")Integer b){
        return a+b;
    }

    @GetMapping(value = "/info")
    public String info(){
        return "Hello World!";
    }

    @GetMapping("/session/{name}")
    public String sessionTest(HttpSession httpSession,@PathVariable("name")String name){
        httpSession.setAttribute("name",name.toString());
        return "OK";
    }

    @GetMapping("/login")
    public ModelAndView loginPage(){
        return new ModelAndView("login");
    }


    @GetMapping("/session")
    public String session(HttpSession session){
        return session.getAttribute("name").toString();
    }

    @GetMapping("/")
    public String main(){
        return "HELLO WORLD!";
    }

    @RequestMapping(value = "/me")
    public Principal user(Principal user){
        Map<String,String> map = new LinkedHashMap<String, String>();
        map.put("name",user.getName()) ;
        return user ;
    }

    @GetMapping(value = "/cookie/{browser}")
    public String cookie(@PathVariable("browser")String browser, HttpServletRequest request,HttpSession session){
        Object sessionBrowser = session.getAttribute("browser");
        if(sessionBrowser == null) {
            System.out.println("不存在session，设置browser="+browser);
            session.setAttribute("browser",browser);
        } else {
            System.out.println("存在session,browser"+browser);
        }
        Cookie[] cookies =request.getCookies();
        if(cookies!=null && cookies.length>0){
            for(Cookie cookie:cookies){
                System.out.println(cookie.getName() + ":"+cookie.getValue());
            }
        }
        return "OK";
    }

//    @RequestMapping("/error")
//    public String error(){
//        return "error";
//    }
}
